package com.example.back.Controller;

import com.example.back.Annotation.UserLoginToken;
import com.example.back.Entity.Comment;
import com.example.back.Repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 评价模块，
 */
@RestController
@RequestMapping("comment")
public class CommentController {
    @Autowired
    private CommentRepository commentRepository;

    //查询对应产品的评论
    @UserLoginToken
    @GetMapping("/list/{pId}")
    public List<Comment> findAllByProductId(@PathVariable("pId") long pId) {
        return commentRepository.findAllByCommentProductId(pId, Sort.by(Sort.Direction.DESC, "commentTime"));
    }

    //评论
    @UserLoginToken
    @PostMapping("")
    public boolean addNewComment(@RequestBody Comment comment) {
        try {
            comment.setCommentTime(new Date());
            commentRepository.save(comment);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    //删除评论
    @UserLoginToken
    @DeleteMapping("{cid}")
    public boolean deleteCommentById(@PathVariable("cid") long cid) {
        try {
            commentRepository.deleteByCommentId(cid);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
